#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
预制件节点名称批量重命名脚本（修正版）
用于将Unity预制件文件中的Unicode编码的中文节点名称替换为英文
"""

import os
import re
import shutil
from pathlib import Path

# 节点名称映射表
NODE_NAME_MAPPING = {
    # 顶部统计相关
    "收款总数背景色": "Revenue_Total_Background",
    "收款总数背景色-值": "Revenue_Total_Value",
    "吃码总数背景色": "Eat_Code_Total_Background", 
    "吃码总数背景色-值": "Eat_Code_Total_Value",
    "上报总数背景色": "Report_Total_Background",
    "上报总数背景色-值": "Report_Total_Value",
    "文本": "Text",
    
    # 下注数据相关
    "号码数据预制件-内容": "BetData_Content",
    "号码数据预制件-内容1": "BetData_Content1", 
    "号码数据预制件-标题": "BetData_TableHeader",
    "名称信息": "Name_Info",
    "具体名节点": "Specific_Name_Node",
    "具体名": "Specific_Name",
    "号码信息1": "Number_Info_1",
    "号码信息2": "Number_Info_2", 
    "号码信息3": "Number_Info_3",
    "号码信息4": "Number_Info_4",
    "数据行1": "Data_Row_1",
    "号码背景色": "Number_Background",
    "号码": "Number",
    "总下注输入框背景色": "Total_Bet_Input_Background",
    "行1-总下注输入框": "Row1_Total_Bet_Input",
    "吃码输入框背景色": "Eat_Code_Input_Background",
    "上报数输入框背景色": "Report_Input_Background",
    "总下注背景色": "Total_Bet_Background",
    "吃码数背景色": "Eat_Code_Background",
    "上报数背景色": "Report_Background",
    "表格头部": "Table_Header",
    "文字": "Text",
    "空格": "Spacer",
    "名称节点": "Name_Node",
    "名称": "Name",
    
    # 风险数据相关
    "号码风险预制件-名称": "RiskData_Header",
    "号码风险预制件-数据": "RiskData_Item",
    "号码风险预制件-容器": "RiskData_Container",
    "吃码数": "Eat_Code_Count",
    "风险值": "Risk_Value",
    "风险值背景色": "Risk_Value_Background",
    "吃码数背景色": "Eat_Code_Count_Background",
}

def chinese_to_unity_unicode(chinese_text):
    """将中文字符串转换为Unity格式的Unicode转义序列（大写）"""
    unicode_escaped = chinese_text.encode('unicode_escape').decode('ascii')
    # 将小写的unicode转义序列转换为大写
    return re.sub(r'\\u([0-9a-f]{4})', lambda m: f'\\u{m.group(1).upper()}', unicode_escaped)

def backup_file(file_path):
    """备份原文件"""
    backup_path = f"{file_path}.backup"
    if not os.path.exists(backup_path):  # 避免重复备份
        shutil.copy2(file_path, backup_path)
        print(f"已备份: {backup_path}")

def replace_node_names_in_file(file_path):
    """替换单个文件中的节点名称"""
    print(f"处理文件: {file_path}")
    
    # 备份原文件
    backup_file(file_path)
    
    # 读取文件内容
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # 记录替换次数
    replacements = {}
    
    # 替换节点名称
    for chinese_name, english_name in NODE_NAME_MAPPING.items():
        # 将中文转换为Unity格式的Unicode转义序列
        unity_unicode = chinese_to_unity_unicode(chinese_name)
        
        # 匹配 m_Name: "Unity Unicode转义序列" 的模式
        pattern = rf'm_Name: "{re.escape(unity_unicode)}"'
        replacement = f'm_Name: "{english_name}"'
        
        # 计算替换次数
        count = len(re.findall(pattern, content))
        if count > 0:
            replacements[chinese_name] = count
            content = re.sub(pattern, replacement, content)
    
    # 写回文件
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(content)
    
    # 输出替换结果
    if replacements:
        print(f"  替换完成:")
        for name, count in replacements.items():
            print(f"    {name} -> {NODE_NAME_MAPPING[name]} ({count}次)")
    else:
        print(f"  未发现需要替换的中文节点名称")
    
    return len(replacements)

def test_unicode_conversion():
    """测试Unicode转换功能"""
    test_strings = ["吃码总数背景色-值", "收款总数背景色-值", "文本"]
    print("Unity Unicode转换测试:")
    for s in test_strings:
        unity_unicode = chinese_to_unity_unicode(s)
        print(f"  {s} -> {unity_unicode}")
    print()

def process_prefabs():
    """处理所有预制件文件"""
    prefab_dir = Path("Assets/Prefabs")
    
    if not prefab_dir.exists():
        print(f"错误: 目录 {prefab_dir} 不存在")
        return
    
    # 测试Unicode转换
    test_unicode_conversion()
    
    # 获取所有预制件文件
    prefab_files = list(prefab_dir.glob("*.prefab"))
    
    if not prefab_files:
        print("未找到预制件文件")
        return
    
    print(f"找到 {len(prefab_files)} 个预制件文件")
    print("=" * 50)
    
    total_files_modified = 0
    
    for prefab_file in prefab_files:
        modified_count = replace_node_names_in_file(prefab_file)
        if modified_count > 0:
            total_files_modified += 1
        print("-" * 30)
    
    print("=" * 50)
    print(f"处理完成! 共修改了 {total_files_modified} 个文件")
    print("\n注意事项:")
    print("1. 原文件已备份为 .backup 文件")
    print("2. 请在Unity中重新导入资源")
    print("3. 建议测试修改后的预制件是否正常工作")

if __name__ == "__main__":
    process_prefabs() 